package com.javakc.pms.instruction.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javakc.pms.instruction.entity.Instruction;
import com.javakc.pms.instruction.mapper.InstructionMapper;
import com.javakc.pms.instruction.service.InstructionService;
import com.javakc.servicebase.config.InstructionQuery;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class Instrucationlmpl extends ServiceImpl<InstructionMapper,Instruction> implements InstructionService  {

    @Override
    public void findPageInstruction(Page<Instruction> instructionPage, InstructionQuery instructionQuery) {
        QueryWrapper<Instruction> queryWrapper = new QueryWrapper<>();
        if(!ObjectUtils.isEmpty(instructionQuery)){
            if(!ObjectUtils.isEmpty(instructionQuery.getName())){
                queryWrapper.like("name",instructionQuery.getName());
            }
          if (!ObjectUtils.isEmpty(instructionQuery.getBeginDate())) {
            queryWrapper.ge("gmt_create", instructionQuery.getBeginDate());
          }
          if (!ObjectUtils.isEmpty(instructionQuery.getEndDate())) {
            queryWrapper.lt("gmt_create", instructionQuery.getEndDate());
          }
        }
        queryWrapper.orderByDesc("gmt_create");
        baseMapper.selectPage(instructionPage,queryWrapper);
    }

    /**
     * 导出
     */
    @Override
    public void exportExcel(HttpServletResponse response) {

        // ## 设置表头值
        String[] titles = {"指令名称", "优先级", "指令类型", "指令描述"};
        // ## 1.创建workbook,对应一个Excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        // ## 2.在workbook中创建一个sheet
        HSSFSheet hssfSheet = workbook.createSheet();
        // ## 3.在sheet中添加表头,第0行
        HSSFRow hssfRow = hssfSheet.createRow(0);
        // ## 4.在第0行设置表头数据
        for (int i = 0; i < titles.length; i++) {
            hssfRow.createCell(i).setCellValue(titles[i]);
        }

        // ## 5.查询并写入数据
        List<Instruction> instructionList = this.list();
        if (null != instructionList) {
            for (int i = 0; i < instructionList.size(); i++) {
                Instruction instruction = instructionList.get(i);
                // ## 创建行
                HSSFRow row = hssfSheet.createRow(i + 1);
                row.createCell(0).setCellValue(instruction.getName());
                row.createCell(1).setCellValue(instruction.getPriority());
                row.createCell(2).setCellValue(instruction.getInType());
                row.createCell(3).setCellValue(instruction.getInDescribe());
            }
        }
        String fileName = new String(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

        try {
            // ## 6.将Excel文件输出到客户端浏览器
            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入
     * @param file
     */
    @Override
    @Transactional
    public void importExcel(MultipartFile file) {

        try {
            // ## 获取文件流
            InputStream inputStream = file.getInputStream();
            // 创建workbook接口
            // ## 声明一个Excel接口
            Workbook workbook = null;
            // ## 根据文件后缀赋予不同POIExcel对象
            if (file.getOriginalFilename().endsWith(".xlsx")) {
                // ## 处理2007版及以上Excel
                workbook = new XSSFWorkbook(inputStream);
            } else {
                // ## 处理2003版本Excel
                workbook = new HSSFWorkbook(inputStream);
            }
            // 得到sheet总数
            int numberOfSheets = workbook.getNumberOfSheets();
            for(int i =0;i<numberOfSheets;i++){
                //获取shett
                Sheet sheet = workbook.getSheetAt(i);
                //得到row总数
                int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
                List<Instruction> list = new ArrayList<>();
                // ## 循环所有的行,j从1开始,因为0为第一行,第一行为表头
                for (int j = 1; j < physicalNumberOfRows; j++) {
                    // ## 每循环一次,通过当前下标一行一行的获取
                    Row row = sheet.getRow(j);
                   Instruction instruction = new Instruction();
                   instruction.setName(row.getCell(0).getStringCellValue());
                   instruction.setPriority((int) row.getCell(1).getNumericCellValue());
                   instruction.setInType(row.getCell(2).getStringCellValue());
                   instruction.setInDescribe(row.getCell(3).getStringCellValue());
                    list.add(instruction);
                }
                // ## 批量添加
                this.saveBatch(list);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
